package com.by.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.by.constants.ThumbConstant;
import com.by.utils.RedisKeyUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 补偿任务
 *
 * @author lzh
 */
@Component
@Slf4j
public class SyncThumbToDbCompensatoryJob {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private SyncThumbToDbJob syncThumbToDbJob;

    @Scheduled(cron = "0 0 2 * * *")
    public void run() {
        log.info("开始补偿数据...");
        Set<String> thumbKeys = redisTemplate.keys(RedisKeyUtils.getTempThumbKey("") + "*");
        Set<String> needHandleDataSet = new HashSet<>();
        if (CollUtil.isEmpty(thumbKeys)) {
            return;
        }
        thumbKeys.stream().filter(ObjUtil::isNotNull)
                .forEach(thumbKey -> needHandleDataSet.add(thumbKey.replace(
                        ThumbConstant.TEMP_THUMB_KEY_PREFIX.formatted(""), ""
                )));

        if (CollUtil.isEmpty(needHandleDataSet)) {
            log.warn("没有需要补偿的数据...");
            return;
        }
        // 补偿数据
        for (String date : needHandleDataSet) {
            syncThumbToDbJob.syncThumbToDbByDate(date);
        }
        log.info("临时数据补偿完成...");
    }
}
